'use strict';

app.controller('LoginController', ['$rootScope', '$scope', '$window', '$state', '$location', function ($rootScope, $scope, $window, $state, $location) {
    $scope.login = function () {
        $scope.auth = {};
        $scope.auth.msg = null;
        $scope.auth.buttonDisable = true;
        // Try to login
        $.post('j_spring_security_check', {
                username: $scope.username,
                password: $scope.password
            },
            function (data) {
                $scope.auth.buttonDisable = false;
                if (data.success) {
                    if ($rootScope.needLogin && angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
                        var toState = $rootScope.cacheUrlState.toState;
                        var toParams = $rootScope.cacheUrlState.toParams;
                        $state.go(toState.name, toParams, {reload : true, inherit:false});

                        //window.location.href = $rootScope.absUrl;
                    } else {
                        $state.go('app.home', {}, {reload : true});
                    }
                    $rootScope.main = data.entity;
                    if(data.entity) {
                        $rootScope.authorities = data.entity.authorities;
                    }
                    $rootScope.needLogin = false;
                } else {
                    $scope.auth.msg = data.msg;
                    $scope.$apply();
                }

                $rootScope.cacheUrlState = undefined;
                $rootScope.needLogin = false;
            }, "json");
    };
}]);